﻿using AutoScaleHelper;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Extensions.ManagedClient;
using System;
using System.Collections.Generic;
using System.Windows.Forms;


namespace Tool
{
    public partial class MonitorForm : Form
    {
        AutoScale autoScale = new AutoScale();

        private IManagedMqttClient mqttClient;//客户端mqtt对象

        Random random = new Random();

        private List<double> data = new List<double>();  // 数据源

        private bool _isLoaded = false;

        public MonitorForm()
        {
            InitializeComponent();
            autoScale.SetContainer(this);
        }

        private void MonitorForm_Load(object sender, EventArgs e)
        {
            _isLoaded = true;
            var factory = new MqttFactory();
            mqttClient = factory.CreateManagedMqttClient();//创建客户端对象
                                                           //绑定断开事件
            /*            mqttClient.UseDisconnectedHandler(async ee =>
                        {
                            //WriteLog("与服务器之间的连接断开了，正在尝试重新连接");
                            // 等待 5s 时间
                            await Task.Delay(TimeSpan.FromSeconds(5));
                            try
                            {
                                mqttClient.UseConnectedHandler(tt =>
                                {
                                    MessageBox.Show(">>> 连接到服务成功");
                                });
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show($"重新连接服务器失败:{ex}");
                            }
                        });*/

            //绑定接收事件
            mqttClient.UseApplicationMessageReceivedHandler(aa =>
            {
                try
                {
                    string msg = aa.ApplicationMessage.ConvertPayloadToString();
                    this.textBox1.Text = ">>> 消息：" + msg + "，QoS =" + aa.ApplicationMessage.QualityOfServiceLevel +
                    "，客户端=" + aa.ClientId + "，主题：" + aa.ApplicationMessage.Topic;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"+ 消息 = " + ex.Message);
                }
            });

            mqttClient.UseConnectedHandler(ee =>
            {
                var topicFilterBulder = new TopicFilterBuilder().WithTopic("test/topic/01").Build();
                mqttClient.SubscribeAsync(topicFilterBulder);
              
                MessageBox.Show(">>> 连接到服务成功");
            });
        }


        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (_isLoaded)
            {
                this.SuspendLayout();
                autoScale.UpdateControlsLayout();
                this.ResumeLayout();
            }
         
        }

        private void ClickButton_Click(object sender, EventArgs e)
        {
            //
            if (timer1.Enabled == false)
            {
                timer1.Enabled = true;
            }
            else
            {
                timer1.Enabled = false;
            }
        }

        //Timer 事件
        private void timer1_Tick(object sender, EventArgs e)
        {
            // 随机生成一个数据
            double value = random.Next(0, 101);

            // 添加到数据源中
            data.Add(value);

            // 如果数据源超过了一定长度，就删除最前面的数据
            if (data.Count > 100)
            {
                data.RemoveAt(0);
            }
            //绑定数据并刷新Chart控件
            chart1.Series[0].Points.DataBindY(data);
            chart1.Refresh();
        }


        /**
         * 关闭窗口触发回调
         */
        private async void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (mqttClient != null)
            {
                if (mqttClient.IsStarted)
                {
                    await mqttClient.StopAsync();
                }
                mqttClient.Dispose();
            }
        }


        private async void button1_Click(object sender, EventArgs e)
        {
            var mqttClientOptions = new MqttClientOptionsBuilder()
              .WithClientId("1111")
              .WithTcpServer("122.156.219.170", int.Parse("20000"))
              .WithCredentials("hldz", "hldz2019#");
            var options = new ManagedMqttClientOptionsBuilder()
                      .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                      .WithClientOptions(mqttClientOptions.Build())
                      .Build();
            //开启
            await mqttClient.StartAsync(options);
            this.button1.Enabled = false;
        }
    }
}
